Language Basics
Variables
In Java programming language defines the following kinds of variables:
- Instance Variables (Non-Static Fields)
- Technically speaking objects store their individual states in "non-static fields", that is, fields that declared without the
static
keyword. Non-static fields are also known as instance variables, because their values are unique to each instance of a class (to each object, in other words). ThecurrentSpeed
of one bicycle is independent from thecurrentSpeed
of another.
- Technically speaking objects store their individual states in "non-static fields", that is, fields that declared without the
- Class Variables (Static Fields)
- A class variable is any field declared with the
static
modifier. This tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of geras for a particular kind of bicycle could be marked asstatic
since the same number of geras will apply to all instances. Additionally the keywordfinal
could be added to indicate that the number of gears will never change.
- A class variable is any field declared with the
- Local Variables
- Similar to how object stores its data in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (
int count = 0;
). Local variables are only visible to the methods in which they are declared, they are not accessible from the rest of the class.
- Similar to how object stores its data in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (
- Parameters
- Recall that the signature for
main
method ispublic static void main(String[] args)
. Here, theargs
variables is the parameter to the method. The important thing to remember is that parameters are always classified as "variables" and not as "fields". This applies to other parameter-accepting constructs as well (such as constructors and exception handlers).
- Recall that the signature for
Naming
The rules and conventions for naming your variables can be summarized as follows:
- Case-sensitive
- An unlimited length sequence of Unicode letters and digits, beginning with a letter, the dollar sign or underscore.
- By convention, always begin your variable names with a letter, not $ or _.
- By convention the dollar sign is never used
- White space is not permitted.
- Subsequent characters may be letters, digits, dollar signs, or underscore characters.
- If the name your choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. If your variable stores a constant value, such as
NUM_GEARS
, capitalize every letter and separate by underscore. By convention the underscore character is never used elsewhere.
Data Types
The eight primitive data types supported by Java programming language are:
byte
: Thebyte
data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127. Thebyte
data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place ofint
where their limits help to clarify your code the fact that a variable's range is limited can serve as a form of documentation.short
: Theshort
data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767.int
" By default theint
data type is a 32-bit signed two's component integer. It has a minimum value of -2^31 and a maximum value of 2^31 - 1. In Java SE 8 and later, you can use theint
data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 2^32 - 1.long
: Thelong
data type is a 64-bit two's complement integer. It has a minimum value of -2^63 and a maximum value of 2^63 - 1.float
: Thefloat
data type is a single-precision 32-bit IEEE 754 floating point number. Use a float instead of double if you need to save memory. This data type should never be used for precise values, such as currency. For that you will need to use thejava.math.BigDecimal
class.double
: Thedouble
data type is a double-precision 64-bit IEEE 754 floating point number. For decimal data types this is generally the default choice. Should never be used for precise values such as currency too.boolean
: Theboolean
data type has only two possible values:true
andfalse
. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information but its "size" isn't something that's precisely defined.- The
char
data type is a single 16-bit Unicode character. It has a minimum value of\u0000
(or 0) and a maximum value of\uFFFFF
(or 65,535 inclusive).
In addition to the eight primitive data types, Java also supports character strings, via the java.lang.String
class. Enclosing your character string within double quotes will automatically create a new String
object. String objects are immutable, once created they cannot be changed.
Default Values
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking the default value will be zero or null
, depending on the data type. Retyping on such values, however, is generally considered to be a bad programming style.
Local variables are not initialized by default. The compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.
Literals
You may have noticed that the new
keyword is not used when initializing a variable of a primitive type. Primitive types are special data types built into the language, they are not objects created from a class. A literal is the source code representation of a fixed value, literals are represented directly in your code without requiring computation.
Integer Literals
An integer literal is of type long
if it ends with the letter L
or l
; otherwise it is of type int
. It is recommended that you use the upper case letter L because the lower case letter L is hard to distinguish from the digit 1.
For general purpose programming you will only use decimal system but if you need to use another symbol, here is how: 0x
indicates hexadecimal. 0b
indicates binary.
Floating-Point Literals
A floating point literal is of type float
if it ends with the letter f
or F
; otherwise its type of double
and can optionally end with the letter d
or D
.
Characters and String Literals
Literals of type char
and String
may contain any Unicode (UTF-16) characters. You can also use Unicode escapes.
Always use single quotes for char
and double quotes for String
literals.
Java also supports special escape sequences such as \b
(backspace), \t
(tab), \n
(new line), \r
(carriage return), \f
(form feed), and \'
(single quote), \"
(double quote), and \\
(backslash).
There's also a special null
literal that can be used as a value for any reference type. It may be assigned to any variable except variables of primitive types. There's little you can do with a null
value beyond testing for its presence. Therefore null
is often used in programs as a marker to indicated that some object is unavailable.
Finally, there's also a special kind of literal called a class literal, formed by taking a type name and appending ".class"; for example, String.class. This refers to the object (of type Class) that represents the type itself.
Arrays
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created.
Each item in an array is called an element. It starts at 0.
This is how conventionally you declare an array: type[] name;
Creating, Initializing, and Accessing Arrays
One way to create an array is with the new
operator.
int[] array;
array = new int[5];
If the statement is missing, then the compiler prints an error.
Alternatively, you can use the shortcut syntax to create an array:
int[] array = new int[5];
Copying Arrays
The System
class has a arraycopy
method that you can use to copy an array.